package com.practice.springboot_01_zwj.service.impl;

import com.practice.springboot_01_zwj.entity.AccountInfo;
import com.practice.springboot_01_zwj.mapper.AccountInfoMapper;
import com.practice.springboot_01_zwj.service.LoginService;
import com.practice.springboot_01_zwj.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * ClassName: LoginServiceImpl <br/>
 * Description: 基于LoginService相关业务逻辑的接口实现 <br/>
 * date: 2024/1/19 9:09 <br/>
 * @author mky <br/>
 * @version v1.0 <br/>
 * @since JDK 17 <br/>
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private AccountInfoMapper accountInfoMapper;
    @Override
    public AccountInfo getAccountInfoByName(String userName) {
        if(userName==null||"".equals(userName)){
            return null;
        }
        return accountInfoMapper.getAccountInfoByName(userName);
    }

    @Override
    public AccountInfo getAccountInfoByNameAndPass(String userName, String password) {
        if(userName == null || userName.isEmpty()){
            return null;
        }
        if(password == null || password.isEmpty()){
            return null;
        }

        // 对传入的密码进行MD5加密
        String encryptedPassword = MD5Util.md5Encrypt(password);
        return accountInfoMapper.getAccountInfoByNameAndPass(userName, encryptedPassword);
    }

    @Override
    public boolean changePassword(String userName, String oldPassword, String newPassword) {
        if (userName == null || userName.isEmpty() ||
                oldPassword == null || oldPassword.isEmpty() ||
                newPassword == null || newPassword.isEmpty()) {
            return false;
        }

        // 1. 验证旧密码是否正确
        String encryptedOldPassword = MD5Util.md5Encrypt(oldPassword);
        AccountInfo accountInfo = accountInfoMapper.getAccountInfoByNameAndPass(userName, encryptedOldPassword);

        if (accountInfo == null) {
            // 旧密码不正确
            return false;
        }

        // 2. 对新密码进行MD5加密
        String encryptedNewPassword = MD5Util.md5Encrypt(newPassword);

        // 3. 更新密码
        int result = accountInfoMapper.updatePassword(userName, encryptedNewPassword);

        return result > 0;
    }
}
